package com.reger.datasource.core;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

public class TempDataSource extends ReferenceDataSource {

	private static final Logger log = LoggerFactory.getLogger(TempDataSource.class);

	private final Map<String, ? extends DataSource> dataSourceMap;
	private final String dbName;
	private final String refDataSourceName;
	private final SqlHandler sqlHandler;

	private final String useDb;

	public TempDataSource(Map<String, ? extends DataSource> dataSourceMap, String refDataSourceName, String dbName) {
		super();
		this.dataSourceMap = dataSourceMap;
		this.refDataSourceName = refDataSourceName;
		this.dbName = dbName;
		this.useDb = "use " + dbName + ";";
		this.sqlHandler=new TempSqlHandler();
	}

	public TempDataSource(DataSource referenceDataSource, String dbName) {
		super();
		super.referenceDataSource = referenceDataSource;
		this.dbName = dbName;
		this.useDb = "use " + dbName + ";";
		this.refDataSourceName = null;
		this.dataSourceMap = null;
		this.sqlHandler=new TempSqlHandler();
	}
	
	@Override
	public DataSource getReferenceDataSource() {
		Assert.isTrue(dataSourceMap.containsKey(refDataSourceName), refDataSourceName + "是不存在的，请检查");
		return dataSourceMap.get(refDataSourceName);
	}
 

	@Override
	public Connection getConnection() throws SQLException {
		return this.useDb(super.getConnection());
	}

	@Override
	public Connection getConnection(String username, String password) throws SQLException {
		return this.useDb(super.getConnection(username, password));
	}

	public String getDbName() {
		return dbName;
	}

	private Connection useDb(final Connection connection) throws SQLException {
		connection.prepareCall(this.useDb).executeQuery();
		log.debug("获取{}的链接", dbName); 
		return new TempConnection(connection,sqlHandler) ;
	}

}
